package com.share.example.selenium.service.amazon.seller;

import com.alibaba.fastjson.JSON;
import com.share.common.utils.DateExtUtil;
import com.share.common.utils.DateUtil;
import com.share.common.utils.DelayUtil;
import com.share.example.selenium.enums.BusinessEnum;
import com.share.example.selenium.enums.OperateStatusEnum;
import com.share.common.exceptions.FormFixException;
import com.share.common.exceptions.LoginException;
import com.share.common.exceptions.PageCheckException;
import com.share.common.exceptions.UrlCheckException;
import com.share.example.selenium.model.amazon.seller.ClosePromoteForm;
import com.share.example.selenium.model.amazon.seller.ClosePromoteTask;
import com.share.example.selenium.model.amazon.seller.PromoteForm;
import com.share.example.selenium.model.amazon.seller.PromoteTask;
import com.share.example.selenium.service.AbsDriver;
import com.share.example.selenium.utils.DriverUtil;
import com.share.example.selenium.utils.ElementUtil;
import com.share.example.selenium.utils.UsDateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Data
@Slf4j
@Service
public class AmazonSellerPromotionService extends AbsDriver {
    private AtomicInteger createErrCount = new AtomicInteger(0);    //创建促销活动-错误计数器
    private AtomicInteger closeErrCount = new AtomicInteger(0);    //关闭促销活动-错误计数器
    private final int MAX_ERR_COUNT = 3;

    private final static String BIZ_CODE = BusinessEnum.AMAZON_BUY.code;
    private final static String LOGIN_URL_PRE = "https://sellercentral.amazon.com/ap/signin";//登录页前缀
    private final static String PROMOTION_MANAGE_URL = "https://sellercentral.amazon.com/promotions/manage";//促销活动首页地址
    private final static String PROMOTION_NEW_URL = "https://sellercentral.amazon.com/promotions/new";//促销活动首页地址
    private final static String PROMOTION_PREVIEW_URL_PRE = "https://sellercentral.amazon.com/promotions/new/preview";//促销预览页
    private final static String PROMOTION_SUBMIT_URL_PRE = "https://sellercentral.amazon.com/promotions/new/submit";//促销提交页
    private final static String CLOSE_PROMOTION_URL = "https://sellercentral.amazon.com/promotions/manage#&pType=STATUS&tab=manage-your-promotions&psType=TRACKING_ID";//关闭促销也买你
    private final static String END_PROMOTION_URL = "https://sellercentral.amazon.com/promotions/end";//提交变成这个链接

    @Autowired
    protected WebDriver driver;

    @Override
    public void reInitDriver(WebDriver driver) {
        this.driver = driver;
    }

    //时间递增
    public List<PromoteForm> batchCreatePromotion(String asin, Integer benefit, Date startUsDateTime, Date endUsDateTime, int cycleNum, Integer orderWay) {
        List<PromoteForm> reList = new LinkedList<>();

        List<String> linkList = new LinkedList<>();
        List<PromoteTask> taskList = new LinkedList<>();

        String promotionName = baseConfService.getPromoteNameByAsins(asin);

        //创建任务
        int add = 0;
        while (true) {
            Date date = UsDateUtil.addHourToDate(startUsDateTime, add++);
            if ((date.getTime() > endUsDateTime.getTime()) || (add > 72)) { //最多输入3天
                break;
            }

            for (int i = 1; i <= cycleNum; i++) {
                //生成任务
                PromoteTask task = new PromoteTask(benefit, date, Integer.toString(i));
                task.setAsin(asin);
                task.setPromotionName(promotionName);
                taskList.add(task);

                //生成link
                String usDateTime = UsDateUtil.toYYYYMMDDHHMMSS(date);
                String link = String.format("http://127.0.0.1:8521/selenium/amazon/seller/createPromotion?promotionSuffix=%s&benefit=%s&asin=%s&usDateTime=%s", i, benefit, asin, usDateTime);
                linkList.add(link);
            }
        }

        log.info("任务列表:");
        log.info(String.join(System.lineSeparator(), linkList));

        //执行任务
        Collections.shuffle(taskList);//先打乱顺序,再排序
        if (orderWay != null) {
            Comparator<PromoteTask> sort = null;
            if (orderWay == 1) {
                sort = Comparator.comparing(PromoteTask::getStartDateTime).thenComparing(PromoteTask::getPromotionSuffix);
            } else if (orderWay == 2) {
                sort = Comparator.comparing(PromoteTask::getPromotionSuffix).thenComparing(PromoteTask::getStartDateTime);
            }

            if (sort != null) {
                taskList = taskList.stream().sorted(sort).collect(Collectors.toList());
            }
        }
        //记录日志
        String status = CollectionUtils.isEmpty(taskList) ? "1" : "2";
        operateLogService.insertLog(BIZ_CODE, "待创建活动-列表", status, null, JSON.toJSONString(taskList), new Date(), driver.getWindowHandle());

        int index = 0;
        int size = taskList.size();
        String batchId = DateExtUtil.getDateTime();
        for (PromoteTask task : taskList) {
            index++;
            String strDateTime = UsDateUtil.toYYYY_MM_DD_HH_MM_SS(task.getStartDateTime());
            log.info("批量创建促销,共{}个人任务,即将处理第{}个任务,benefit={},usStartDateTime={},promotionSuffix={}", size, index, task.getBenefit(), strDateTime, task.getPromotionSuffix());
            PromoteForm promotion = createPromotion(task, false);

            //记录活动详情
            promoteDetailService.insertCreatePromotion(batchId, task, promotion);

            //多次失败,则退出
            if (promotion != null && OperateStatusEnum.SUCCESS.code.equals(promotion.getStatus())) {
                createErrCount.set(0);
                reList.add(promotion);
            } else {
                createErrCount.incrementAndGet();
            }
            if (createErrCount.get() >= MAX_ERR_COUNT) {
                log.info("连续{}次异常,终止批量任务,当前任务编号index={}", MAX_ERR_COUNT, index);
                break;
            }
        }

        return reList;
    }

    //创建一个活动
    public PromoteForm createPromotion(PromoteTask task, boolean cleanErrCount) {
        //清除计数器
        if (cleanErrCount) {
            createErrCount.set(0);
        }

        String errMsg = null;
        PromoteForm promotion = null;
        String status = OperateStatusEnum.EXCEPTION.code;
        try {
            Boolean aBoolean = openPromotionpage();
            if (aBoolean) {
                try {
                    promotion = fixForm(task);
                    status = OperateStatusEnum.SUCCESS.code;
                } catch (FormFixException e) {
                    errMsg = e.getMessage();
                    log.error("表单填写异常", e);
                } catch (PageCheckException e) {
                    errMsg = e.getMessage();
                    log.error("页面检测异常", e);
                } catch (UrlCheckException e) {
                    errMsg = e.getMessage();
                    log.error("url检测异常", e);
                } catch (Exception e) {
                    errMsg = e.getMessage();
                    if (errMsg.contains("no such element") && errMsg.contains("timeouts")) {
                        log.info("定位不到元素,可能是网络异常,强制延时15s");
                        DelayUtil.sleepSecond(15);
                    }
                    log.error("执行异常", e);
                }
            }
        } catch (Exception e) {
            errMsg = e.getMessage();
            log.error("执行异常", e);
        }

        String otherMsg = null;
        if (promotion == null) {
            otherMsg = null;
        } else {
            otherMsg = JSON.toJSONString(promotion);
            promotion.setStatus(status);
        }

        String title = "创建促销活动-" + task.getStartDate() + "_" + task.getStartTime() + "-" + task.getPromotionSuffix();
        dingdingCreatePromote(task, promotion, errMsg);//发送到钉钉

        operateLogService.insertLog(BIZ_CODE, title, status, errMsg, otherMsg, new Date(), driver.getWindowHandle());
        return promotion;
    }

    //打开促销页面
    private Boolean openPromotionpage() {
        //打开创建促销页面---需要加载页面
        /** 访问 https://sellercentral.amazon.com/promotions/manage
         会刷新到 https://sellercentral.amazon.com/promotions/manage/ref=xx_promomgr_favb_xx
         */
        driver.get(PROMOTION_MANAGE_URL);
        DelayUtil.sleepRangSecond(2, 5);

        //登录检查
        String loginCheckUrl = driver.getCurrentUrl();
        boolean toLogin = loginCheckUrl.contains(LOGIN_URL_PRE);
        if (toLogin) {
            createErrCount.set(10);//直接跳出
            log.info("打开创建促销活动页面,系统跳转到了登录页面url={}", loginCheckUrl);
            throw new LoginException("打开创建促销活动页面,系统跳转到了登录页面url=" + loginCheckUrl);
        }

        //点击创建促销 下面的创建
        WebElement ele_cj = driver.findElement(By.id("epmMPCLink"));
        ele_cj.click();
        DelayUtil.sleepRangSecond(3, 4);

        String currentUrl = driver.getCurrentUrl();
        boolean contains = currentUrl.contains(PROMOTION_NEW_URL);
        if (contains) {
            log.info("打开填写促销活动信息页面成功,url={}", currentUrl);
        } else {
            log.info("打开填写促销活动信息页面失败,url={}", currentUrl);
        }
        return contains;
    }

    //填写促销表单页面
    private PromoteForm fixForm(PromoteTask task) throws FormFixException, UrlCheckException, PageCheckException {
        PromoteForm promotion = new PromoteForm();
        promotion.setCommitDateTime(DateUtil.getDateTime());

        String usStartDate = task.getStartDate();
        String usStartTime = task.getStartTime();
        String usEndDate = task.getEndDate();

        //商品下拉列表-----完整的提示
        WebElement ele_goods = driver.findElement(By.id("purchaseItemType"));
        ele_goods.click();
        DelayUtil.sleepRangSecond(1, 3);
        WebElement ele_goods1 = driver.findElement(By.id("purchaseItemTypeNative_1"));
        String goodsName = ele_goods1.getText(); //LED Strip Lights with Bluetooth and APP Control,Multicolor RGB LED Light Strips
        promotion.setGoodsName(goodsName);
        if (goodsName.contains("ASIN") && goodsName.contains("列表")) {
            ele_goods1.click();
            log.info("选择产品goods={}", goodsName);
        } else {
            throw new FormFixException("选择产品goods异常");
        }

        //填充-ASIN
        WebElement ele_asin = driver.findElement(By.id("purchasedItemString"));
        ele_asin.clear();
        ElementUtil.inputValue(ele_asin, task.getAsin(), 100, 400);
        String asin = ele_asin.getAttribute("value");
        promotion.setAsin(asin);
        log.info("促销-商品asin={}", asin);
        if (!asin.equals(task.getAsin())) {
            throw new FormFixException("填写asin异常,asin=" + asin);
        }

        //填写折扣率
        WebElement ele_benefit = driver.findElement(By.id("benefitValue"));
        ele_benefit.clear();//先请空再填写
        ele_benefit.sendKeys(task.getBenefit() + "");
        int tmpBenefit = Integer.parseInt(ele_benefit.getAttribute("value"));
        promotion.setBenift(tmpBenefit);
        if (tmpBenefit > 60) {
            createErrCount.set(10);//直接跳出
            log.info("折扣率填写的过大,benefit={}", tmpBenefit);
            throw new FormFixException("折扣率填写的过大异常,benefit=" + tmpBenefit);
        }
        if (tmpBenefit != task.getBenefit()) {
            createErrCount.set(10);//直接跳出
            log.info("折扣率填写的异常,benefit={}", tmpBenefit);
            throw new FormFixException("折扣率填写的异常,benefit=" + tmpBenefit);
        }
        log.info("填写折扣率benefit={}", tmpBenefit);

        //促销开始日期
        WebElement ele_promotion_start_date = driver.findElement(By.id("startDate"));
        ele_promotion_start_date.clear();
        ElementUtil.inputValue(ele_promotion_start_date, usStartDate, 100, 400);
        String tmpStartDate = ele_promotion_start_date.getAttribute("value");
        checkDate(tmpStartDate);
        promotion.setStartDate(tmpStartDate);
        log.info("促销-开始日期usStartDate={}", tmpStartDate);

        //选择时间
        WebElement ele_promotion_start_time = driver.findElement(By.id("startTime"));
        ele_promotion_start_time.click();
        DelayUtil.sleepRangSecond(1, 3);
        int hour = UsDateUtil.getHourFromTime(usStartTime);
        WebElement start_time = driver.findElement(By.id("startTimeNative_" + hour));
        start_time.click();
        DelayUtil.sleepMillis(300);
        String fixStartTime = driver.findElement(By.xpath("//*[@id=\"startTime\"]/span/span/span")).getText();
        promotion.setStartTime(fixStartTime);
        log.info("促销-开始时间usStartTime={}", fixStartTime);

        //促销结束日期
        WebElement ele_promotion_end_date = driver.findElement(By.id("endDate"));
        ele_promotion_end_date.clear();
        ElementUtil.inputValue(ele_promotion_end_date, usEndDate, 100, 600);
        String tmpEndDate2 = ele_promotion_end_date.getAttribute("value");
        checkDate(tmpEndDate2);
        promotion.setEndDate(tmpEndDate2);
        log.info("促销-结束日期usEndDate={}", tmpEndDate2);

        //结束时间
        WebElement ele_promotion_end_time = driver.findElement(By.id("endTime"));
        ele_promotion_end_time.click();
        DelayUtil.sleepRangSecond(1, 3);
        WebElement endTime = driver.findElement(By.id("endTimeNative_24"));
        endTime.click();
        DelayUtil.sleepMillis(300);
        String fixEndTime = driver.findElement(By.xpath("//*[@id=\"endTime\"]/span/span/span")).getText();
        promotion.setEndtTime(fixEndTime);
        log.info("促销-结束时间usEndTime={}", fixEndTime);

        //促销的产品
        String subfix = task.getBenefit() + "-" + UsDateUtil.toMMDDHH(task.getStartDateTime()) + "-" + task.getPromotionSuffix();
        String promotionName = task.getPromotionName() + " " + subfix;
        WebElement ele_promotion_item = driver.findElement(By.id("promotionTitle"));
        ele_promotion_item.clear();
        ElementUtil.inputValue(ele_promotion_item, promotionName, 30, 200);
        String fixPromotionName = ele_promotion_item.getAttribute("value");
        promotion.setPromotionName(fixPromotionName);
        log.info("促销活动名称promotionName={}", fixPromotionName);

        //无限结算
        WebElement ele_wuxianjisuan = driver.findElement(By.id("unlimitedProductUnlimitedOrderRadio"));
        ele_wuxianjisuan.click();


        //点击查看----初步提交
        log.info("即将开始预览活动");
        WebElement ele_view = driver.findElement(By.id("a-autoid-3-announce"));
        ele_view.click();
        DelayUtil.sleepRangSecond(3, 5);
        String curReviewUrl = driver.getCurrentUrl();
        if (!curReviewUrl.startsWith(PROMOTION_PREVIEW_URL_PRE)) {
            log.info("预览促销活动失败,curReviewUrl={}", curReviewUrl);
            throw new UrlCheckException("预览促销活动页面异常");
        }

        //错误页面校验----填写表单后,点击查看,如果提示异常---则提前退出----必须是list查询
        List<WebElement> ele_list_over = driver.findElements(By.id("formBean.errors"));
        if (ele_list_over.size() > 0) {
            WebElement ele_over = ele_list_over.get(0);
            String overMsg = ele_over.getText();
            if (StringUtils.isNotBlank(overMsg) && overMsg.contains("指定时间段内的促销已经达到最大数量") && overMsg.contains("请重新选择促销开始时间和结束时间")) {
                createErrCount.set(10);//直接跳出
                log.info("填写表单后,点击查看,提示异常={}", overMsg);
                throw new PageCheckException(overMsg);
            }
        }

        //获取优惠码
        WebElement ele_couponCode = driver.findElement(By.id("claimCodeText"));
        String couponCode = ele_couponCode.getText();
        promotion.setCouponCode(couponCode);
        log.info("优惠码={}", couponCode);

        // 点击提交
        log.info("即将提交活动");
        WebElement ele_commit = driver.findElement(By.id("a-autoid-1-announce"));
        ele_commit.click();
        DelayUtil.sleepRangSecond(2, 4);
        String curCommitUrl = driver.getCurrentUrl();
        if (!curCommitUrl.startsWith(PROMOTION_SUBMIT_URL_PRE)) {
            log.info("提交促销活动失败,curCommitUrl={}", curCommitUrl);
            throw new UrlCheckException("提交促销活动页面异常");
        }

        // 获取促销链接
        WebElement ele_link = driver.findElement(By.xpath("//*[@id=\"epmPromotionSuccessMessage\"]/div/div/p[1]"));
        String linkText = ele_link.getText();
        String promotionLink = getLink(linkText);
        promotion.setPromotionLink(promotionLink);
        log.info("促销链接promotionLink={}", promotionLink);

        if (StringUtils.isNotBlank(promotionLink)) {
            String[] split = promotionLink.split("/");
            String code = split[split.length - 1];
            promotion.setPromotionCode(code);
        }

        return promotion;
    }

    private String getLink(String promotionLink) {
        if (StringUtils.isBlank(promotionLink)) {
            return null;
        }
        try {
            String[] https = promotionLink.split("http");
            String link = "http" + https[1].split(" ")[0];
            return link;
        } catch (Exception e) {
            log.error("原始链接信息linktext={}", promotionLink, e);
            return null;
        }
    }

    private Boolean checkDate(String strDate) throws FormFixException {
        try {
            Date date = UsDateUtil.strD2Date(strDate);
            if (date == null) {
                throw new FormFixException("日期格式检测异常");
            }
            return true;
        } catch (Exception e) {
            throw new FormFixException("日期格式执行转换异常");
        }
    }

    //返回已删除或者待删除的任务列表
    public List<ClosePromoteForm> batchClosePromotion(boolean realDlete, ClosePromoteTask task) {
        List<ClosePromoteForm> reList = new LinkedList<>();

        //1.查询所有的任务
        List<ClosePromoteForm> list = listClosePromoteForm(task);
        int size = list.size();
        list = list.stream().sorted(Comparator.comparing(ClosePromoteForm::getStartDateTime).thenComparing(ClosePromoteForm::getPromotionName)).collect(Collectors.toList());
        log.info("赛选出来的任务size={},list={}", size, JSON.toJSONString(list));

        //记录操作日志
        String status = CollectionUtils.isEmpty(list) ? "1" : "2";
        String title = realDlete ? "待删除活动-列表" : "获取待删除活动-列表";
        operateLogService.insertLog(BIZ_CODE, title, status, null, JSON.toJSONString(list), new Date(), driver.getWindowHandle());

        //2.是否执行删除--关闭所有的任务
        int index = 0;
        String batchId = DateExtUtil.getDateTime();
        if (realDlete) {
            //变量每一项
            for (ClosePromoteForm item : list) {
                index++;
                log.info("共{}条,正在处理第{}条,startDate={},promoteName={}", size, index, item.getStartDateTime(), item.getPromotionName());
                Boolean delSuccess = null;
                String link = item.getLink();
                if (StringUtils.isBlank(link) || !link.startsWith("http")) {
                    continue;
                }

                try {
                    delSuccess = closePromotion(batchId, item, false);
                } catch (Exception e) {
                    log.error("关闭促销活动异常,link={}", link);
                }

                //多次失败检验
                if (delSuccess != null && delSuccess) {
                    reList.add(item);
                    closeErrCount.set(0);
                } else {
                    closeErrCount.incrementAndGet();
                }
                if (closeErrCount.get() >= MAX_ERR_COUNT) {
                    log.info("关闭促销活动,连续{}次异常,终止批量任务link={}", closeErrCount.get(), link);
                    break;
                }
            }
        } else {
            //查看-待删除
            reList.addAll(list);
        }
        return reList;
    }

    private List<ClosePromoteForm> listClosePromoteForm(ClosePromoteTask task) {
        final int startPage = task.getStartPage(); //取值为1-9,默认取值为3
        final int dealSize = task.getDealSize(); //默认取值为1
        List<ClosePromoteForm> reList = new LinkedList<>();

        //打开创建促销管理页面---需要加载页面
        Boolean aBoolean = openClosePromotionPage();
        if (!aBoolean) {
            return reList;
        }

        //翻页条获取
        List<WebElement> ele_page_bar = getPageBar();
        log.info("翻页获取链接信息,开始页号startPage={},待处理页数dealSize={}", startPage, dealSize);
        int num = 0; //计数器
        if (ele_page_bar.size() >= 3 + startPage) {//上一页,~,下一页,1,2,3,
            if (startPage != 1) {//第一页不需要点击
                ele_page_bar.get(startPage).click();
                DelayUtil.sleepRangSecond(2, 4);
            }

            do {
                //计数器
                num++;

                //数据分析
                int realPageIndex = startPage + num - 1;
                log.info("活动链接信息获取-即将提取页号为{}的数据", realPageIndex);
                List<ClosePromoteForm> onePageList = analysisOnePageTr(task);
                if (!CollectionUtils.isEmpty(onePageList)) {
                    reList.addAll(onePageList);
                }

                //提前退出
                if (num >= dealSize) {
                    break;
                }

                //滑到最下面
                DriverUtil.scrollTop(driver, 2000);
                DelayUtil.sleepRangMillis(800, 1200);

                //翻页操作
                log.info("即将开始翻页,当前处于第{}页", realPageIndex);
                ele_page_bar = getPageBar();
                WebElement ele_next_page = ele_page_bar.get(ele_page_bar.size() - 1);
                String aClass = ele_next_page.getAttribute("class");
                if (aClass.equals("a-last")) {
                    ele_next_page.click();
                    DelayUtil.sleepRangSecond(3, 4);
                } else if (aClass.contains("a-disabled")) {
                    //不能点击----说明是最后一页
                    log.info("下一页按钮不可点击,当前处于最后一页");
                    break;
                } else {
                    log.info("获取下一页按钮异常");
                    //数据异常
                    break;
                }
            } while (num < dealSize);
        }
        return reList;
    }

    //翻页条-获取
    private List<WebElement> getPageBar() {
        By pageBarPath = By.xpath("//*[@id=\"managepromotionstable-pagination\"]/ul/li");
        List<WebElement> ele_page_bar = driver.findElements(pageBarPath);
        return ele_page_bar;
    }

    //删除一个活动
    public Boolean closePromotion(String batchId, ClosePromoteForm form, boolean cleanErrCount) throws LoginException {
        if (cleanErrCount) {
            closeErrCount.set(0);
        }

        boolean re = false;
        String errMsg = null;
        try {
            //打开新的tab页
            String url = form.getLink();
            driver.get(url);
            DelayUtil.sleepRangSecond(2, 3);

            //登录检查
            String loginCheckUrl = driver.getCurrentUrl();
            boolean toLogin = loginCheckUrl.contains(LOGIN_URL_PRE);
            if (toLogin) {
                closeErrCount.set(10);
                log.info("打开促销链接页面,系统跳转到了登录页面url={}", loginCheckUrl);
                throw new LoginException("打开促销链接页面,系统跳转到了登录页面,当前url=" + loginCheckUrl);
            }

            //获取删除按钮
            WebElement ele_jieshu = driver.findElement(By.id("a-autoid-3"));
            String text = ele_jieshu.getText();
            if (text.contains("结束促销")) {
                ele_jieshu.click();//点击 结束促销
                DelayUtil.sleepRangMillis(1000, 1500);

                //点击确认结束
                WebElement ele_commit = driver.findElement(By.id("a-autoid-4-announce"));
                String commitText = ele_commit.getText();
                if (commitText.contains("提交")) {
                    ele_commit.submit();
                    DelayUtil.sleepRangSecond(2, 3);
                    String currentUrl = driver.getCurrentUrl();
                    if (currentUrl.contains(END_PROMOTION_URL)) {
                        //关闭成功
                        re = true;
                    }
                }
            } else if (text.contains("查看更改历史记录")) {
                log.info("促销活动早已关闭-link={}", url);
                re = true;
            }
        } catch (LoginException e) {
            errMsg = e.getMessage();
            log.info("系统没有登录", e);
        } catch (Exception e) {
            errMsg = e.getMessage();
            log.info("执行异常", e);
        }

        //发送订单消息
        dingdingClosePromote(form, re, errMsg);

        //活动详情中加日志
        promoteDetailService.insertClosePromotion(batchId, form, re, errMsg);

        String title = "删除促销活动-" + form.getLink();
        operateLogService.insertLog(BIZ_CODE, title, re ? "2" : "1", errMsg, JSON.toJSONString(form), new Date(), driver.getWindowHandle());

        return re;
    }

    //分析某一页的数据
    private List<ClosePromoteForm> analysisOnePageTr(ClosePromoteTask task) {
        List<ClosePromoteForm> reList = new LinkedList<>();

        //分析数据
        List<WebElement> ele_trs = driver.findElements(By.xpath("//*[@id=\"managepromotionstable\"]/div[5]/div/table/tbody/tr"));
        int size = ele_trs.size();
        for (int i = 1; i < size; i++) {
            ClosePromoteForm form = new ClosePromoteForm();

            //获取id
            WebElement ele_tr = ele_trs.get(i);
            String rowId = ele_tr.getAttribute("id");

            //订单数量过滤
            WebElement ele_ordersField = driver.findElement(By.id(rowId + "-ordersField"));
            String orderNum = ele_ordersField.getText();
            form.setOrderNum(orderNum);
            if (StringUtils.isNotBlank(orderNum)) {
                Integer order = null;
                //订单数量校验----数值也校验下
                try {
                    order = Integer.parseInt(orderNum.trim());
                } catch (Exception e) {
                    continue;
                }

                if (task.getOrderNum() != null) {
                    if (order > task.getOrderNum()) {
                        continue;  //跳过
                    }
                }
            }


            //活动名字过滤
            WebElement ele_titleField = driver.findElement(By.id(rowId + "-titleField"));
            String promotionName = ele_titleField.getText();
            form.setPromotionName(promotionName);
            if (!CollectionUtils.isEmpty(task.getPromotionNames())) {
                if (StringUtils.isBlank(promotionName)) {
                    continue;
                }
                boolean contains = promotionNamesContainsFliter(promotionName, task.getPromotionNames());
                if (!contains) {
                    continue;
                }
            }

            //开始时间过滤
            WebElement ele_startDateField = driver.findElement(By.id(rowId + "-startDateField"));
            String tmpStartDateTime = ele_startDateField.getText();
            form.setStartDateTime(tmpStartDateTime);
            if (StringUtils.isNotBlank(task.getStartFilter1()) || StringUtils.isNotBlank(task.getStartFilter2())) {
                if (StringUtils.isBlank(tmpStartDateTime) || tmpStartDateTime.length() < 10) {
                    continue;
                }
            }
            if (StringUtils.isNotBlank(task.getStartFilter1())) {
                if (compareTo(tmpStartDateTime, task.getStartFilter1()) < 0) {
                    continue;
                }
            }
            if (StringUtils.isNotBlank(task.getStartFilter2())) {
                if (compareTo(tmpStartDateTime, task.getStartFilter2()) > 0) {
                    continue;
                }
            }

            //结束时间过滤
            WebElement ele_endDateField = driver.findElement(By.id(rowId + "-endDateField"));
            String tmpEndDateTime = ele_endDateField.getText();
            form.setEndDateTime(tmpEndDateTime);
            if (StringUtils.isNotBlank(task.getEndFilter1()) || StringUtils.isNotBlank(task.getEndFilter2())) {
                if (StringUtils.isBlank(tmpEndDateTime) || tmpEndDateTime.length() < 10) {
                    continue;
                }
            }
            if (StringUtils.isNotBlank(task.getEndFilter1())) {
                if (compareTo(tmpEndDateTime, task.getEndFilter1()) < 0) {
                    continue;
                }
            }
            if (StringUtils.isNotBlank(task.getEndFilter2())) {
                if (compareTo(tmpEndDateTime, task.getEndFilter2()) > 0) {
                    continue;
                }
            }

            WebElement ele_trackingIdField = driver.findElement(By.id(rowId + "-trackingIdField"));
            WebElement a = ele_trackingIdField.findElement(By.tagName("a"));
            String href = a.getAttribute("href");//https://sellercentral.amazon.com/promotions/view?promotionId=A1YVL1AGV81I43
            if (!href.startsWith("http")) {
                href = "https://sellercentral.amazon.com" + href;
            }
            String trackName = a.getText();
            form.setLink(href);
            form.setTrackName(trackName);

            reList.add(form);
        }
        return reList;
    }

    //打开关闭促销活动页面
    private Boolean openClosePromotionPage() {
        //打开创建促销管理页面---需要加载页面
        driver.get(CLOSE_PROMOTION_URL);
        DelayUtil.sleepRangSecond(2, 4);

        //登录检查
        String loginCheckUrl = driver.getCurrentUrl();
        boolean toLogin = loginCheckUrl.contains(LOGIN_URL_PRE);
        if (toLogin) {
            createErrCount.set(10);//直接跳出
            log.info("打开促销活动列表页面,系统跳转到了登录页面url={}", loginCheckUrl);
            throw new LoginException("打开促销活动列表页面,系统跳转到了登录页面url=" + loginCheckUrl);
        }

        return true;
    }

    /**
     * text  2023-11-14 23:59 PST
     *
     * @param text
     * @param strDateTime
     * @return
     */
    private static int compareTo(String text, String strDateTime) {
        String standarDateTime = null;
        String[] s = text.trim().split(" ");
        if (s != null && s.length == 3) {
            String date = s[0];
            String strDate = date.replace("-", "");
            if (date.length() != 10) {
                String[] d = date.split("-");
                String year = d[0];
                String method = d[1];
                String day = d[2];
                strDate = year + (method.length() == 2 ? method : "0" + method) + (day.length() == 2 ? day : "0" + day);
            }
            String time = s[1].replace(":", "") + "00";
            standarDateTime = strDate + time;
        }

        return standarDateTime.compareTo(strDateTime);
    }

    //名字过滤
    private static boolean promotionNamesContainsFliter(String text, List<String> names) {
        if (StringUtils.isBlank(text)) {//一般不能为空
            return false;
        }

        if (CollectionUtils.isEmpty(names)) {
            return true;
        } else {
            int size = names.size();
            int count = 0;
            for (String str : names) {
                if (text.contains(str)) {
                    count++;
                }
            }

            if (count == size) {
                return true;
            } else {
                return false;
            }
        }
    }


    public static void main(String[] args) {
        System.out.println(compareTo("2023-11-24 23:59 P77ST", "20231114235911"));
    }
}
